package utils

import (
	"context"
	"fmt"

	"admin_template/bff/admin/hertz_gen/base"
	"gitee.com/byx_darwin/go-tools/kitex/rpc_error"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func Reply(ctx *app.RequestContext, code int, obj interface{}) {
	ctx.JSON(code, obj)
}

func ReplyWithBindErr(ctx *app.RequestContext,
	c context.Context,
	log hlog.CtxLogger, err error) {
	path := string(ctx.Path())
	msg := fmt.Sprintf("(%s)bind err:%v", path, err.Error())
	log.CtxErrorf(c, msg)
	reply := base.BaseReply{
		Code: base.ErrCode_Fail,
		Msg:  msg,
	}
	Reply(ctx, consts.StatusOK, &reply)
}
func ReplyWithErr(ctx *app.RequestContext,
	c context.Context,
	format, publicMsg string,
	log hlog.CtxLogger,
	err error) {
	if err != nil {
		errType, _ := rpc_error.ParseBizStatusError(err)
		path := string(ctx.Path())
		msg := fmt.Sprintf("%d(%s)%s:%s", errType, path, format, err.Error())
		log.CtxErrorf(c, msg)
		switch errType {
		case rpc_error.ErrorTypeInvalid:
			reply := base.BaseReply{
				Code: consts.StatusInternalServerError,
				Msg:  msg,
			}
			Reply(ctx, consts.StatusOK, &reply)
		case rpc_error.ErrorTypeDataRepeat:
			reply := base.BaseReply{
				Code: consts.StatusInternalServerError,
				Msg:  publicMsg,
			}
			Reply(ctx, consts.StatusOK, &reply)
		case rpc_error.ErrorTypeDataInvalid:
			reply := base.BaseReply{
				Code: consts.StatusInternalServerError,
				Msg:  publicMsg,
			}
			Reply(ctx, consts.StatusOK, &reply)
		default:
			ctx.AbortWithMsg(err.Error(), consts.StatusInternalServerError)
		}
		return
	}
	reply := base.BaseReply{
		Code: consts.StatusOK,
		Msg:  publicMsg,
	}
	Reply(ctx, consts.StatusOK, &reply)
}
